<template>
  <div class="cptCon">
    <el-row type="flex"
            justify="space-between">
      <el-col :span="6">
        <el-button type="primary"
                   @click="uploadModel=true">导入模型</el-button>
      </el-col>
      <el-col :span='18'>
        <el-form :inline="true"
                 :model="form"
                 class="float-right">
          <el-form-item label="更新时间">
            <el-date-picker v-model="form.time"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="getUpdateTime(form.time)">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-input placeholder="请输入模型名称"
                      v-model="form.modelName"
                      @keyup.enter.native="getData"
                      clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       @click="getData">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <p class="float-right"
           style="margin-right:10px">{{ this.$route.query.project_name }}</p>
      </el-col>
      <el-col :span='24'>
        <el-table :data="tableData"
                  style="width: 100%">
          <el-table-column label="序号"
                           align="center">
            <template slot-scope="scope">
              <span>{{ scope.$index+(page - 1)*10 + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="模型名称"
                           align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.model_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="轻量化状态"
                           align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.status== 0 ? '转化中' :(scope.row.status== 1 ? '转化成功' :(scope.row.status== 2
                ? '转化失败' :'转换异常'))}}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间"
                           align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.updated_at}}</span>
            </template>
          </el-table-column>
          <el-table-column label="模型展示"
                           align="center">
            <template slot-scope="scope">
              <!-- <span @click="goModel(scope.row.status,scop.row.detail_url)">详情</span> -->
              <el-button v-if='scope.row.status==1'
                         type="success"
                         icon="el-icon-check"
                         size="mini"
                         circle
                         @click="goModel(scope.row)"></el-button>
              <el-button v-else
                         type="info"
                         icon="el-icon-warning"
                         size="mini"
                         circle></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           width="245px">
            <template slot-scope="scope">
              <el-button type="text"
                         @click="edit(scope.row)">编辑</el-button>
              <el-button type="text"
                         @click="deleteRow(scope.row)">删除</el-button>
              <el-button type="text"
                         @click="download(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24">
        <el-pagination style="text-align: center;padding-top:40px;"
                       @current-change="handleCurrentChange"
                       layout="total, prev, pager, next, jumper"
                       :total=pageTotal>
        </el-pagination>
      </el-col>
      <el-dialog title="导入模型"
                 :visible.sync="uploadModel"
                 width="30%">
        <el-form :model="uploadForm"
                 label-width="100px"
                 :rules="rules"
                 ref="uploadForm">
          <el-form-item label="模型名称"
                        prop="name">
            <el-input v-model="uploadForm.name"></el-input>
          </el-form-item>
          <el-form-item label="项目模型"
                        prop="rvtUrl">
            <el-input v-model="uploadForm.rvtUrl"
                      v-show="false"></el-input>
            <el-upload action=""
                       :http-request="addRvtModel"
                       :limit="1"
                       accept=".rvt"
                       ref="uploadRvt">
              <el-button size="small"
                         type="primary"
                         class="el-icon-upload"> 上 传</el-button>
              <span style="color:red;font-size:12px;margin-left:15px">rvt格式</span>
            </el-upload>
            <el-progress v-if="uploadForm.rvtPercentage!=0 && uploadForm.rvtPercentage!=100"
                         :text-inside="true"
                         :stroke-width="18"
                         :percentage="Math.floor(uploadForm.rvtPercentage)"></el-progress>
          </el-form-item>
          <el-form-item label="轻量化模型"
                        prop="miniUrl">
            <el-input v-model="uploadForm.miniUrl"
                      v-show="false"></el-input>
            <el-upload class="upload-demo"
                       action=""
                       :http-request="addMiniModel"
                       :limit="1"
                       accept=".mini"
                       ref="uploadMini">
              <el-button size="small"
                         type="primary"
                         class="el-icon-upload"> 上 传</el-button>
              <span style="color:red;font-size:12px;margin-left:15px">mini格式</span>
            </el-upload>
            <el-progress v-if="uploadForm.miniPercentage!=0 && uploadForm.miniPercentage!=100"
                         :text-inside="true"
                         :stroke-width="18"
                         :percentage="Math.floor(uploadForm.miniPercentage)"></el-progress>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="uploadModel = false">取 消</el-button>
          <el-button type="primary"
                     @click="saveUploadModel('uploadForm')">保 存</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑模型"
                 :visible.sync="editModel"
                 width="30%">
        <el-form ref="editForm"
                 :model="editForm"
                 :rules="editRules"
                 status-icon
                 label-width="100px">
          <el-form-item label="模型名称"
                        prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="项目模型"
                        prop="rvtUrl">
            <el-input v-model="editForm.rvtUrl"
                      v-show="false"></el-input>
            <el-upload action=""
                       :http-request="modifyRvtModel"
                       :limit="1"
                       accept=".rvt"
                       ref="modifyRvt">
              <el-button size="small"
                         type="primary"
                         class="el-icon-upload"> 上 传</el-button>
              <span style="color:red;font-size:12px;margin-left:15px">rvt格式</span>
            </el-upload>
            <el-progress v-if="editForm.rvtPercentage!=0 && editForm.rvtPercentage!=100"
                         :text-inside="true"
                         :stroke-width="18"
                         :percentage="Math.floor(editForm.rvtPercentage)"></el-progress>
          </el-form-item>
          <el-form-item label="轻量化模型"
                        prop="miniUrl">
            <el-input v-model="editForm.miniUrl"
                      v-show="false"></el-input>
            <el-upload class="upload-demo"
                       action=""
                       :http-request="modifyMiniModel"
                       :limit="1"
                       accept=".mini"
                       ref="modifyMini">
              <el-button size="small"
                         type="primary"
                         class="el-icon-upload"> 上 传</el-button>
              <span style="color:red;font-size:12px;margin-left:15px">mini格式</span>
            </el-upload>
            <el-progress v-if="editForm.miniPercentage!=0 && editForm.miniPercentage!=100"
                         :text-inside="true"
                         :stroke-width="18"
                         :percentage="Math.floor(editForm.miniPercentage)"></el-progress>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editModel = false">取 消</el-button>
          <el-button type="primary"
                     @click="modifyUploadModel('editForm')">保 存</el-button>
        </span>
      </el-dialog>
      <el-dialog title="下载模型"
                 :visible.sync="downloadModel"
                 width="30%">
        <el-form ref="downForm"
                 :model="downForm"
                 label-width="100px">
          <el-form-item label="模型名称">
            <el-input v-model="downForm.name"></el-input>
          </el-form-item>
          <el-form-item label="项目模型">
            <el-button type="primary"
                       icon="el-icon-download"
                       size="small"
                       @click="downFile(downForm.rvtUrl)">.RVT下载</el-button><span style="margin-left:10px;color:#999;display:table-cell;vertical-align:bottom">文件大小：{{downForm.rvtSize}}</span>
          </el-form-item>
          <el-form-item label="轻量化模型">
            <el-button type="primary"
                       icon="el-icon-download"
                       size="small"
                       @click="downFile(downForm.miniUrl)">.mini下载</el-button><span style="margin-left:10px;color:#999999;display:table-cell;vertical-align:bottom">文件大小：{{downForm.miniSize}}</span>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="downloadModel = false">取 消</el-button>
          <el-button type="primary"
                     @click="dialogVisible = false">保 存</el-button>
        </span>
      </el-dialog>
      <!-- 删除模型确认弹窗 -->
      <el-dialog title="删除"
                 :visible.sync="deleteVisible"
                 width="30%">
        <span>是否删除<span class='delete-span'>{{delete_name}}</span>?</span>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="deleteVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="sureDelete">确 定</el-button>
        </span>
      </el-dialog>

    </el-row>
  </div>
</template>
<script>
import { modelManageApi } from '@/services/ProjectCenter'
import { UploadFileApi } from '@/services/UserPermission'
import { standardCodeApi } from '@/services/StandardCode'
import axios from 'axios'
import qs from 'qs'
import OSS from 'ali-oss'
export default {
  data () {
    return {
      deleteVisible: false,
      delete_name: "",
      delete_id: "",
      form: {
        time: [],
        modelName: '',
      },
      created_at_greater: "",
      created_at_less: "",
      uploadForm: {
        name: '',
        rvtUrl: '',
        rvtSize: '',
        miniUrl: '',
        miniSize: '',
        miniPercentage: 0,
        rvtPercentage: 0,

      },
      editForm: {
        name: '',
        rvtUrl: '',
        rvtSize: '',
        miniUrl: '',
        miniSize: '',
        miniPercentage: 0,
        rvtPercentage: 0,
        id: '',
      },
      downForm: {
        name: '',
        rvtUrl: '',
        rvtSize: '',
        miniUrl: '',
        miniSize: '',
      },
      pageTotal: 1,
      page: 1,
      tableData: [],
      uploadModel: false,
      downloadModel: false,
      editModel: false,
      bucketUrl: '',
      rules: {
        name: [
          { required: true, message: '请输入模型名称', trigger: 'blur' }
        ],
        rvtUrl: [
          { required: true, message: '请上传模型', trigger: 'change' }
        ],
        miniUrl: [
          { required: true, message: '请上传模型', trigger: 'change' }
        ],
      },
      editRules: {
        name: [
          { required: true, message: '请输入模型名称', trigger: 'blur' }
        ],
        rvtUrl: [
          { required: true, message: '请上传模型', trigger: 'change' }
        ],
        miniUrl: [
          { required: true, message: '请上传模型', trigger: 'change' }
        ],
      }
    }
  },
  methods: {
    //时间筛选
    getUpdateTime (data) {
      //上传开始时间
      if (!data) {
        this.created_at_greater = ""
        this.created_at_less = ""
        this.getData()
      } else {
        var stime = new Date(data[0])
        var y = stime.getFullYear();
        var m = stime.getMonth() + 1;
        var d = stime.getDate();
        var start = y + '-' + m + '-' + d
        this.created_at_greater = start
        // //上传结束时间
        var stime1 = new Date(data[1])
        var y = stime1.getFullYear();
        var m = stime1.getMonth() + 1;
        var d = stime1.getDate();
        var start1 = y + '-' + m + '-' + d
        this.created_at_less = start1
        this.getData()
      }
    },
    //获取数据
    getData () {
      modelManageApi.getProjectData({
        params: {
          project_id: this.$route.query.project_id,
          per_page: 10,
          model_name: this.form.modelName,
          created_at_greater: this.created_at_greater,
          created_at_less: this.created_at_less
        }
      }).then(res => {
        this.tableData = res.data.data
        this.pageTotal = res.data.total;
      }, err => {
        console.log(err)
      })
      // axios.get('admin/design/getModelList', { params: { page: this.page, name: this.form.modelName, mintime: this.form.time[0], maxtime: this.form.time[1], project_id: this.$route.query.id, uuid: sessionStorage.getItem("uuid") } }, {
      //   headers: {
      //     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      //   }
      // }).then(res => {
      //   this.tableData = res.data.data.data;
      //   this.pageTotal = res.data.data.count;
      // }, err => {
      //   console.log(err)
      // })
    },
    //上传rvt模型
    addRvtModel (data) {
      var _this = this;
      var client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: _this.bucketUrl,
      })
      var address = 'upload/design/' + this.$route.query.project_id + '/' + new Date().getTime() + Math.floor(Math.random() * 10) + '.rvt';
      // var address = 'upload/design/24/' + new Date().getTime() + Math.floor(Math.random()*10)+'.rvt';
      client.multipartUpload(address, data.file, {
        progress: function (percentage) {
          _this.uploadForm.rvtPercentage = percentage * 100   //上传的进度

        }
      }).then((res) => {
        _this.uploadForm.rvtUrl = (res.name).substr(7);
        _this.uploadForm.rvtSize = Math.round(data.file.size / 1024 / 1024) + 'M';
      }).catch((err) => {
        console.log(err)
      })
    },
    //上传mini模型
    addMiniModel (data) {
      var _this = this;
      var client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: _this.bucketUrl,
      })
      var address = 'upload/design/' + this.$route.query.project_id + '/' + new Date().getTime() + Math.floor(Math.random() * 10) + '.Mini';
      // var address = 'upload/design/24/' + new Date().getTime() + Math.floor(Math.random()*10)+'.Mini';
      client.multipartUpload(address, data.file, {
        progress: function (percentage) {
          _this.uploadForm.miniPercentage = percentage * 100   //上传的进度

        }
      }).then((res) => {
        _this.uploadForm.miniUrl = (res.name).substr(7);
        _this.uploadForm.miniSize = Math.round(data.file.size / 1024 / 1024) + 'M';
      }).catch((err) => {
        console.log(err)
      })
    },
    //保存上传模型数据
    saveUploadModel (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modelManageApi.saveModel({
            data: {
              project_id: this.$route.query.project_id,
              model_name: this.uploadForm.name,
              rvt_file: this.uploadForm.rvtUrl,
              rvt_size: this.uploadForm.rvtSize,
              mini_file: this.uploadForm.miniUrl,
              mini_size: this.uploadForm.miniSize
            }
          }).then(res => {
            if (res.code == '1') {
              this.$message.success('保存成功')
              this.uploadModel = false;
              this.getData();
              this.refresh();
              this.$refs[formName].resetFields();
              this.$refs.uploadRvt.clearFiles()
              this.$refs.uploadMini.clearFiles()
            } else {
              this.$message.error('保存失败')
              this.$refs[formName].resetFields();
            }
          }, err => {
            console.log(err)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //修改rvt模型
    modifyRvtModel (data) {
      var _this = this;
      var client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: _this.bucketUrl,
      })
      var address = 'upload/design/' + this.$route.query.project_id + '/' + new Date().getTime() + Math.floor(Math.random() * 10) + '.rvt';
      // var address = 'upload/design/24/' + new Date().getTime() + Math.floor(Math.random()*10)+'.rvt';
      client.multipartUpload(address, data.file, {
        progress: function (percentage) {
          _this.editForm.rvtPercentage = percentage * 100   //上传的进度
        }
      }).then((res) => {
        _this.editForm.rvtUrl = (res.name).substr(7);
        _this.editForm.rvtSize = Math.round(data.file.size / 1024 / 1024) + 'M';
      }).catch((err) => {
        console.log(err)
      })
    },
    //修改mini模型
    modifyMiniModel (data) {
      var _this = this;
      var client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: _this.bucketUrl,
      })
      var address = 'upload/design/' + this.$route.query.project_id + '/' + new Date().getTime() + Math.floor(Math.random() * 10) + '.Mini'
      // var address = 'upload/design/24/' + new Date().getTime() + Math.floor(Math.random()*10)+'.Mini';
      client.multipartUpload(address, data.file, {
        progress: function (percentage) {
          _this.editForm.miniPercentage = percentage * 100   //上传的进度

        }
      }).then((res) => {
        _this.editForm.miniUrl = (res.name).substr(7);
        _this.editForm.miniSize = Math.round(data.file.size / 1024 / 1024) + 'M';
      }).catch((err) => {
        console.log(err)
      })
    },
    //修改上传模型数据
    modifyUploadModel (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modelManageApi.updateModel({
            data: {
              project_id: this.$route.query.project_id,
              entity_model_id: this.editForm.id,
              model_name: this.editForm.name,
              rvt_file: this.editForm.rvtUrl,
              rvt_size: this.editForm.rvtSize,
              mini_file: this.editForm.miniUrl,
              mini_size: this.editForm.miniSize
            }
          }).then(res => {
            if (res.code == '1') {
              this.$message.success('修改成功')
              this.editModel = false
              this.$refs[formName].resetFields();
              this.getData();
              this.refresh()
              this.$refs.modifyRvt.clearFiles()
              this.$refs.modifyMini.clearFiles()
            } else {
              this.$message({
                showClose: true,
                message: '保存失败',
                type: 'error'
              });
              this.$refs[formName].resetFields();
            }
          }, err => {
            console.log(err)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //跳转页面
    goModel (data) {
      this.$router.push({ path: 'showModel', query: { url: data.model_url } })
    },
    //编辑
    edit (row) {
      this.editModel = true;
      this.editForm.id = row.entity_model_id;
      this.editForm.name = row.model_name;
    },
    download (row) {
      this.downloadModel = true;
      this.downForm.name = row.model_name;
      this.downForm.rvtUrl = row.rvt_file_url;
      this.downForm.rvtSize = row.rvt_size;
      this.downForm.miniUrl = row.mini_file_url;
      this.downForm.miniSize = row.mini_size;
    },
    downFile (url) {
      // var alink = document.createElement('a')
      // alink.href = url
      // alink.download = ''
      // alink.click()
      window.location.href = url;
    },
    //打开删除模型
    deleteRow (row) {
      this.delete_name = row.model_name
      this.deleteVisible = true
      this.delete_id = row.entity_model_id
    },
    //确认删除模型
    sureDelete () {
      modelManageApi.deleteModel({
        data: {
          entity_model_id: this.delete_id
        }
      }).then(res => {
        if (res.code == '1') {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.getData();
          this.deleteVisible = false
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
          this.deleteVisible = false
        }
      }, err => {
        console.log(err)
      })
    },
    refresh () {
      var _this = this;
      let data = [];
      setTimeout(function () {
        for (var i = 0; i < _this.tableData.length; i++) {
          if (_this.tableData[i].status != 1) {
            data.push(_this.tableData[i].entity_model_id)
          }
        };
        if (data.length != 0) {
          var timer = setInterval(() => {
            setTimeout(function () {
              modelManageApi.getModelStat({
                data: {
                  entity_model_id: data.join(',')
                }
              }).then(res => {
                if (res.data.length != 0) {
                  _this.getData();
                }
              }, err => {
                console.log(err)
              })
            }, 0)
            if (data.length == 0) {
              clearInterval(timer)
            }
          }, 3000)
        }
      }, 2000)

    },
    handleCurrentChange (page) {
      this.page = page;
      this.getData();
    },
    getOss () {
      standardCodeApi.getOssAddress({
      }).then(res => {
        this.bucketUrl = res.data.address.split('//')[1].split('.')[0]
        console.log(this.bucketUrl)
      }, err => {
        console.log(err)
      })
    }
  },
  created () {
    this.getOss()
  },
  mounted () {
    this.getData();
    this.refresh();
    // if (location.hostname === 'localhost') {
    //   this.bucketUrl = 'dev-hibuilding-new'
    // } else if (location.hostname === 'dev_front.ihibuilding.cn') {
    //   this.bucketUrl = 'dev-hibuilding-new'
    // } else if (location.hostname === 'test_front.ihibuilding.cn') {
    //   this.bucketUrl = 'dev-hibuilding-new'
    // } else if (location.hostname === 'www.hibuilding.cn') {
    //   this.bucketUrl = 'hibuilding'
    // } else if (location.hostname === 'front.hibuilding.cn') {
    //   this.bucketUrl = 'hibuilding'
    // }
    // else if (location.hostname === 'front-show.hibuilding.cn') {
    //   this.bucketUrl = 'hibuilding'
    // }
  },
}
</script>
<style scoped lang='scss'>
.cptCon {
  padding: 40px;
}
.delete-span {
  color: #1890ff;
  font-weight: bold;
}
</style>